// 
import {
  axiosPostApiInfo, axiosPutApiInfo, axiosDeleteApiInfo,
  axiosGetApiHeader, axiosPostApiHeader, axiosPutApiHeader, axiosDeleteApiHeader,
  axiosGetApiQuery, axiosPostApiQuery, axiosPutApiQuery, axiosDeleteApiQuery,
  axiosGetApiBody, axiosPostApiBody, axiosPutApiBody, axiosDeleteApiBody,
  axiosPostApiResponse
} from '../../api/api'
import vueJsonEditor from 'vue-json-editor';
export default {
  props: [""],
  data() {
    return {
      //选中的接口信息
      apiInfo: {},
      //提交时判断有没有修改，是否POST新增
      apiInfo_old: {},
      selectGroupNmae: "",
      inputApiNmae: "接口名称",
      requestMethod: "GET",
      httpMethod: "HTTP",
      dropdownRequestMethod: [
        { method: "GET" },
        { method: "POST" },
        { method: "DELETE" },
        { method: "PUT" }
      ],
      dropdownHttpMethod: [
        { method: 'HTTP' },
        { method: 'HTTPS' }
      ],
      project: "",
      //接口请求路径
      inputHostPath: "",
      activeName: "header",
      //提交时判断有没有修改，是否POST新增
      headerData_old: [
        {
          api_id: '',
          header_name: "",
          header_value: "",
          header_required: false,
          header_type: "String",
          header_desc: "",
          id: "",
        },
      ],
      queryData_old: [
        {
          api_id: '',
          query_name: "",
          query_value: "",
          query_required: false,
          query_type: "String",
          query_desc: "",
          id: "",
        },
      ],
      bodyData_old: [
        {
          json_data: {},
        },
      ],
      // header表格
      headerData: [
        {
          api_id: '',
          header_name: "",
          header_value: "",
          header_required: false,
          header_type: "String",
          header_desc: "",
          id: "",
        },
      ],
      queryData: [
        {
          api_id: '',
          query_name: "",
          query_value: "",
          query_required: false,
          query_type: "String",
          query_desc: "",
          id: "",
        },
      ],
      //body数据
      bodyData: [
        {
          json_data: {},
        },
      ],
      // header表格选中列表
      headerSelection: [],
      querySelection: [],
      isBodyJson: true,
      responseData: '',
    };
  },
  components: {
    vueJsonEditor,
  },
  created() {
    this.apiInfo = this.$store.state.API_INFO;
    this.apiInfo_old = JSON.parse(JSON.stringify(this.apiInfo));
    //如果是新增的接口，无ID，则不请求数据
    if (this.apiInfo.id) {
      // console.log('新增的接口带ID');
      this.axiosgetApiRequests();
    }
  },
  mounted() {
  },
  methods: {
    /** 接口参数 */
    //发送接口请求
    clickSendApiRequest() {
      //先保存接口信息
      // this.clickSaveApiRequest();
      //请求数据封装
      //接口信息
      //发送请求
      var params = {
        header: this.headerSelection,
        query: this.querySelection,
        body: this.bodyData[0].json_data,
        api_info: this.apiInfo
      };
      //发起请求，接口测试
      axiosPostApiResponse(params).then(res => {
        this.activeName='response';
        this.responseData = res.data;
        if (res.status === 200) {
          //发送成功更新页面
          this.$message({ message: '接口请求成功', type: 'success' })
        } else {
          this.$message.error({
            message: '接口请求失败！！！', duration: 5000
          });
        }
      }).catch((error) => {
        this.activeName='response';
        this.responseData = error
        this.$message.error({ message: error, duration: 5000 })
      }
      )
    },
    //将字符串保存为文档
    exportRaw(name, data) {
      var urlObject = window.URL || window.webkitURL || window;
      var export_blob = new Blob([data]);
      var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
      save_link.href = urlObject.createObjectURL(export_blob);
      save_link.download = name;
      fakeClick(save_link);
    },
    //表格选中事件
    selectHeaderhandle(selection) {
      this.headerSelection = selection;
    },
    selectQueryhandle(selection) {
      this.querySelection = selection;
    },
    //点击保存按钮执行函数,上传请求参数
    clickSaveApiRequest() {
      // apiinfo ,header, query, body,
      this.axiosApiInfo();
      this.axiosApiHeader();
      this.axiosApiQuery();
      this.axiosApiBody();
      this.listLoading = false;
    },
    //保存接口参数
    axiosApiInfo() {
      //如果数据变更，则向服务器保存
      //如果数据相等
      if (JSON.stringify(this.apiInfo_old) == JSON.stringify(this.apiInfo)) {
        this.$message({ message: '接口信息未发生变化', type: 'info' });
        return
      }
      //如果id存在且不为空，则put，否则post
      if (this.apiInfo.hasOwnProperty('id') && this.apiInfo.id !== '') {
        console.log('apiInfo发起PUT请求')
        var params = this.apiInfo;
        //发起请求，修改接口信息
        axiosPutApiInfo(params).then(res => {
          if (res.status === 200) {
            //发送成功更新页面
            for (let i in this.$store.state.API_LIST) {
              if (this.$store.state.API_LIST[i].id === this.apiInfo.id) {
                this.$store.state.API_LIST[i] = this.apiInfo;
                break
              }
            }
            this.$message({ message: '保存接口信息成功', type: 'success' })
          } else {
            this.$message.error({
              message: '保存接口信息失败！！！', duration: 5000
            });
          }
        }).catch((error) =>
        this.$message.error({ message: error })
        )
      } else {
        console.log('apiInfo发起POST请求')
        //根据分组名称查找对应的分组id,将分组id添加进接口信息
        if (this.$store.state.GROUP_NAME !== '') {
          for (let i in this.$store.state.GROUP_LIST) {
            if (this.$store.state.GROUP_NAME === this.$store.state.GROUP_LIST[i].group_name) {
              this.apiInfo['group_id'] = this.$store.state.GROUP_LIST[i].id;
              break
            }
          }
          //如果找不到分组则新建分组
        }
        //保存当前接口名称为全局参数
        var params = this.apiInfo;
        //发起请求，新增接口信息
        axiosPostApiInfo(params).then(res => {
          if (res.status === 201) {
            //返回值带有id,需保存
            this.apiInfo = res.data;
            this.$store.state.API_INFO = res.data;
            this.apiInfo_old = JSON.parse(JSON.stringify(res.data));
            this.$store.state.API_LIST.push(res.data);
            this.$message({ message: '新增接口信息成功', type: 'success' })
            //提示group_id api_name 未定义
          } else {
            this.$message.error({
              message: '新增接口信息失败！！！',
            });
          }
        }).catch((error) =>
        this.$message.error({ message: error, duration: 5000 })
        )
      }
    },
    axiosApiHeader() {
      //如果数据不变
      if (JSON.stringify(this.headerData_old) == JSON.stringify(this.headerData)) {
        this.$message.info('header未发生变化');
        return
      }
      //如果header被删除,则旧数据比新数据长，所以当删除header时，需要连同删除旧数据，防止出现取值不对称
      //循环提交headerData每行的值
      for (let i in this.headerData) {
        //如果数据不变
        if (JSON.stringify(this.headerData_old[i]) == JSON.stringify(this.headerData[i])) {
          continue
        }
        //如果输入为空
        if (!this.headerData[i].hasOwnProperty('header_name') || this.headerData[i].header_name == '') {
          continue
        }
        if (!this.headerData[i].hasOwnProperty('api_id') || this.headerData[i].api_id == '') {
          //插入当前接口id
          if (this.apiInfo.id) {
            this.headerData[i]["api_id"] = this.apiInfo.id
          }
        }
        //如果id存在且不为空，则put,否则post
        if (this.headerData[i].hasOwnProperty('id') && this.headerData[i].id !== '') {
          console.log('header发起PUT请求')
          var params = this.headerData[i];
          //发起请求 修改接口header
          axiosPutApiHeader(params).then(res => {
            if (res.status === 200) {
              this.headerData_old[i] = res.data;
              this.$message({ message: '保存herder参数成功', type: 'success' })
            } else {
              this.$message.error({
                message: '保存接口herder参数失败！！！', duration: 5000
              });
            }
          }).catch((error) =>
          this.$message.error({ message: error, duration: 5000 })
          )
        } else {
          console.log('header发起POST请求')
          var params = this.headerData[i];
          //发起请求 新增接口header
          axiosPostApiHeader(params).then(res => {
            console.log(res);
            if (res.status === 201) {
              //返回值带有id
              this.headerData[i] = JSON.parse(JSON.stringify(res.data));
              this.headerData_old[i] = JSON.parse(JSON.stringify(res.data));
              this.$message({ message: '新增herder参数成功', type: 'success' })
            } else {
              this.$message.error({
                message: '新增接口herder参数失败！！！'
              });
            }
          }).catch((res) =>
          this.$message.error({ message: res, duration: 5000 })
          )
        }
      }

    },
    axiosApiQuery() {
      //如果数据没变
      if (JSON.stringify(this.queryData_old) == JSON.stringify(this.queryData)) {
        this.$message({ message: 'Query未发生变化asd', type: 'info' });
        return
      }
      //循环提交headerData每行的值
      for (let i in this.queryData) {
        //如果数据没变
        if (JSON.stringify(this.queryData_old[i]) == JSON.stringify(this.queryData[i])) {
          continue
        }
        //如果输入为空
        if (!this.queryData[i].hasOwnProperty('query_name') || this.queryData[i].query_name == '') {
          continue
        }
        //如果api_id不存在 或者等于空
        if (!this.queryData[i].hasOwnProperty('api_id') || this.queryData[i].api_id == '') {
          //插入当前接口id
          this.queryData[i]["api_id"] = this.apiInfo.id
        }
        //如果id存在且不为空，则put,否则post
        if (this.queryData[i].hasOwnProperty('id') && this.queryData[i].id !== '') {
          console.log('Query发起PUT请求')
          var params = this.queryData[i];
          //发起请求 修改接口Query
          axiosPutApiQuery(params).then(res => {
            this.listLoading = false;
            if (res.status === 200) {
              this.queryData_old[i] = res.data;
              this.$message({ message: '保存接口Query参数成功', type: 'success' })
            } else {
              this.$message.error({
                message: '保存接口Query参数失败！！！',
              });
            }
          }).catch((error) =>
          this.$message.error({ message: error, duration: 5000 })
          )
        } else {
          console.log('Query发起POST请求')
          var params = this.queryData[i];
          //发起请求 新增接口Query
          axiosPostApiQuery(params).then(res => {
            if (res.status === 201) {
              //返回值带有id
              this.queryData[i] = JSON.parse(JSON.stringify(res.data));
              this.queryData_old[i] = JSON.parse(JSON.stringify(res.data));
              this.$message({ message: '新增接口Query参数成功', type: 'success' });
            } else {
              this.$message.error({
                message: '新增接口Query参数失败！！！', duration: 5000
              });
            }
          }).catch((error) =>
          this.$message.error({ message: error, duration: 5000 })
          )
        }

      }

    },
    axiosApiBody() {
      //如果不是json格式
      if (!this.isBodyJson || this.bodyData.length != 1) {
        if (this.isBodyJson === false) {
          this.$message.error({
            message: "Body数据不是json格式，请修改"
          })
        }
        if (this.bodyData.length != 1) {
          this.$message.error({
            message: "Body数据数组中值有且只能有一个对象,请在json_data中添加数据"
          })
        }
        return
      }
      //如果数据不变
      if (JSON.stringify(this.bodyData) == JSON.stringify(this.bodyData_old)) {
        this.$message({ message: 'Body未发生变化', type: 'info' });
        return
      }
      if (this.bodyData_old[0].hasOwnProperty('api_id')) {
        if (this.bodyData[0].api_id != this.bodyData_old[0].api_id) {
          this.$message({ message: 'body的api_id值不能被修改，已为您改回正确值', type: 'warnning' });
          this.bodyData[0].api_id = this.bodyData_old[0].api_id;
          return
        }
      }
      if (this.bodyData_old[0].hasOwnProperty('id')) {
        if (this.bodyData[0].id != this.bodyData_old[0].id) {
          this.$message({ message: 'body的id值不能被修改，已为您改回正确值', type: 'warnning' });
          this.bodyData[0].id = this.bodyData_old[0].id;
          return
        }
      }
      if (!this.bodyData[0].hasOwnProperty('api_id') || this.bodyData[0].api_id == '') {
        //插入当前接口id
        this.bodyData[0]["api_id"] = this.apiInfo.id
      }
      //如果id存在则PUT 否则post
      if (this.bodyData[0].hasOwnProperty('id')) {
        console.log('Body发起PUT请求')
        var params = this.bodyData[0];
        //发起请求 修改接口Body
        axiosPutApiBody(params).then(res => {
          if (res.status === 200) {
            this.bodyData_old[0] = res.data;
            this.$message({ message: '保存接口Body参数成功', type: 'success' })
          } else {
            this.$message.error({
              message: '保存接口Body参数失败！！！',
              duration: 5000
            });
          }
        }).catch((error) =>
        this.$message.error({ message: error })
        )
      } else {
        console.log('Body发起POST请求')
        this.bodyData[0].json_data = JSON.stringify(this.bodyData[0].json_data)
        var params = this.bodyData[0];
        //发起请求 新增接口Body
        axiosPostApiBody(params).then(res => {
          if (res.status === 201) {
            this.bodyData[0] = res.data;
            this.bodyData_old[0] = JSON.parse(JSON.stringify(res.data));
            this.$message({ message: '新增接口Body参数成功', type: 'success' })
          } else {
            this.$message.error({
              message: '新增接口Body参数失败！！！',
            });
          }
        }).catch((error) =>
        this.$message.error({ message: error })
        )
      }
    },
    // 选择分组
    clickSelectGroupName(groupName) {
      for (let i = 0; i < this.$store.state.GROUP_LIST.length; i++) {
        if (groupName === this.$store.state.GROUP_LIST[i]['group_name']) {
          this.apiInfo.group_id = this.$store.state.GROUP_LIST[i].id
          break
        }
      }
    },
    //选择请求方式
    clickSelectRequestMethod(method) {
      this.apiInfo.request_type = method;
    },
    clickSelectHttpMethod(method) {
      this.apiInfo.http_type = method;
    },

    /** 请求参数 */
    //获取接口参数
    axiosgetApiRequests() {
      var params = { api_id: this.$store.state.API_INFO.id };
      //发起请求 获取项目所有接口信息
      axiosGetApiHeader(params).then(res => {
        this.listLoading = false;
        if (res.status === 200) {
          //将获取到的列表进行状态保存
          if (res.data.length > 0) {
            this.headerData = res.data;
            this.headerData_old = JSON.parse(JSON.stringify(res.data));
            this.$refs.headerRef.toggleAllSelection()
          }
        } else {
          this.$message.error({
            message: '获取接口Herder参数失败！！！',
          });
        }
      }).catch((error) =>
      this.$message.error({ message: error })
      )
      //发起请求 获取项目所有接口信息
      axiosGetApiQuery(params).then(res => {
        this.listLoading = false;
        if (res.status === 200) {
          //将获取到的列表进行状态保存
          if (res.data.length > 0) {
            this.queryData = res.data;
            this.queryData_old = JSON.parse(JSON.stringify(res.data));
            this.$refs.queryRef.toggleAllSelection()
          }
        } else {
          this.$message.error({
            message: '获取接口Query参数失败！！！',
          });
        }
      }).catch((error) =>
      this.$message.error({ message: error })
      )
      //发起请求 获取项目所有接口信息
      axiosGetApiBody(params).then(res => {
        this.listLoading = false;
        if (res.status === 200) {
          //将获取到的列表进行状态保存
          if (res.data.length > 0) {
            this.bodyData = res.data;
            this.bodyData_old = JSON.parse(JSON.stringify(res.data));
          }
        } else {
          this.$message.error({
            message: '获取接口Body参数失败！！！',
          });
        }
      }).catch((error) =>
      this.$message.error({ message: error })
      )
    },
    //
    // tabs 接口请求参数标签页
    handleClickTabs() { },
    //新增行 index为点击的那行索引
    createTableRow(index, row, type) {
      if (type === 'header') {
        var newRow = {
          api_id: this.apiInfo.id,
          header_name: "",
          header_value: "",
          header_required: "true",
          header_type: "String",
          header_desc: "",
        };
        this.headerData.push(newRow);
        this.$refs.headerRef.toggleRowSelection(newRow);
      }
      if (type === 'query') {
        var newRow = {
          api_id: this.apiInfo.id,
          query_name: "",
          query_value: "",
          query_required: "true",
          query_type: "String",
          query_desc: "",
        };
        this.queryData.push(newRow);
        this.$refs.queryRef.toggleRowSelection(newRow);
      }
    },
    saveTableRow(index, row, type) {

    },
    //删除行
    deleteTableRow(index, row, type) {
      console.log(row);
      if (index > 0) {
        if (type === 'header') {
          this.headerData.splice(index, 1);

          //需要发送ajax删除数据 
        }
        if (type === 'query') {
          this.queryData.splice(index, 1);
          ////需要发送ajax删除数据 
        }
      }
    },
    onJsonChange(value) {
      //提交ajax的时候，需检查是否json
      this.bodyData[0] = value;
      if (this.bodyData.length > 1) {
        this.$message.error({
          message: "Body数据数组中值有且只能有一个对象,请在json_data中添加数据"
        })
      }
      this.isBodyJson = true;
      console.log('json格式正确');
    },
    onJsonError() {
      this.isBodyJson = false;
    },
  }
};